var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var cors = require('cors');

const { router: indexRouter, setupWebSocket } = require('./routes/index');
var usersRouter = require('./routes/users');
// var apiRouter = require('./routes/api'); // <--- 假设你会创建一个新的api.js文件

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors());
app.use(logger('dev')); // 保持一个
app.use(express.json()); // 保持一个
app.use(express.urlencoded({ extended: true })); // 保持一个，并设置为true
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', indexRouter);  // 添加 /api 前缀
// app.use('/api', apiRouter); // <--- 在这里注册你的新API路由

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404, `Not Found - ${req.originalUrl}`)); // 包含原始URL
// }); 

// error handler
app.use((err, req, res, next) => {
  console.error('全局错误处理:', err);
  res.status(500).json({
    code: 500,
    message: '服务器错误',
    error: err.message
  });
});
// 创建 HTTP 服务器
const server = require('http').createServer(app);

// 设置 WebSocket
setupWebSocket(server);

// 启动服务器
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

module.exports = app;
